package org.example.service.impl;

import org.example.dto.SaveTestResultDTO;
import org.example.dto.TestDetailDTO;
import org.example.entity.ReactionTestRecord;
import org.example.entity.TestDetail;
import org.example.mapper.ReactionTestRecordMapper;
import org.example.mapper.TestDetailMapper;
import org.example.service.ReactionTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 反应测试服务实现类
 */
@Service
public class ReactionTestServiceImpl implements ReactionTestService {
    
    @Autowired
    private ReactionTestRecordMapper reactionTestRecordMapper;
    
    @Autowired
    private TestDetailMapper testDetailMapper;
    
    /**
     * 保存测试结果
     */
    @Override
    @Transactional
    public Long saveTestResult(SaveTestResultDTO dto, Long userId) {
        // 参数校验
        if (dto == null || userId == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        if (dto.getTestDetails() == null || dto.getTestDetails().isEmpty()) {
            throw new IllegalArgumentException("测试详情不能为空");
        }
        
        // 创建测试记录
        ReactionTestRecord record = new ReactionTestRecord();
        record.setUserId(userId);
        record.setAverageTime(dto.getAverageTime());
        record.setBestTime(dto.getBestTime());
        record.setTotalTests(dto.getTotalTests());
        record.setTestDate(LocalDateTime.now());
        
        // 保存测试记录
        reactionTestRecordMapper.insert(record);
        
        // 保存测试详情
        List<TestDetail> testDetails = new ArrayList<>();
        for (TestDetailDTO detailDTO : dto.getTestDetails()) {
            TestDetail detail = new TestDetail();
            detail.setRecordId(record.getId());
            detail.setReactionTime(detailDTO.getReactionTime());
            detail.setTestNumber(detailDTO.getTestNumber());
            testDetails.add(detail);
        }
        
        // 批量插入测试详情
        if (!testDetails.isEmpty()) {
            testDetailMapper.batchInsert(testDetails);
        }
        
        return record.getId();
    }
    
    /**
     * 获取用户历史记录
     */
    @Override
    public List<ReactionTestRecord> getUserHistory(Long userId, Integer page, Integer size) {
        if (userId == null || page == null || size == null || page <= 0 || size <= 0) {
            throw new IllegalArgumentException("参数无效");
        }
        
        // 设置默认值和限制
        if (size > 100) {
            size = 100;
        }
        
        // 计算偏移量
        int offset = (page - 1) * size;
        
        return reactionTestRecordMapper.selectByUserId(userId, offset, size);
    }
    
    /**
     * 获取用户最佳成绩
     */
    @Override
    public ReactionTestRecord getUserBestResult(Long userId) {
        return reactionTestRecordMapper.selectBestByUserId(userId);
    }
    
    /**
     * 获取排行榜
     */
    @Override
    public List<ReactionTestRecord> getRanking(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 20; // 默认显示前20名
        }
        return reactionTestRecordMapper.selectRanking(limit);
    }
    
    /**
     * 获取测试记录详情
     */
    @Override
    public ReactionTestRecord getTestDetail(Long recordId, Long userId) {
        if (recordId == null || userId == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 获取测试记录
        ReactionTestRecord record = reactionTestRecordMapper.selectById(recordId);
        if (record == null) {
            throw new IllegalArgumentException("测试记录不存在");
        }
        
        // 验证记录归属，确保用户只能查看自己的记录
        if (!record.getUserId().equals(userId)) {
            throw new SecurityException("无权访问该测试记录");
        }
        
        // 获取测试详情
        List<TestDetail> details = testDetailMapper.selectByRecordId(recordId);
        record.setTestDetails(details);
        
        return record;
    }
}